<template>
  <div>
    <quillEditor
      class="editor"
      ref="myQuillEditor"
      v-model="content"
      :options="editorOption"
    >
      <div class="vm-eidtor-toolbar" slot="toolbar">
        <el-button
          type="link"
          icon="eye"
          class="toolbar-module"
          @click="onPreview"
          v-if="needPreview"
        >
          点击预览
        </el-button>
      </div>
    </quillEditor>

    <form action="" method="post" enctype="multipart/form-data" :id="formId">
      <input
        style="display: none;"
        :id="uniqueId"
        type="file"
        name="cover"
        multiple
        accept="image/jpg,image/jpeg,image/png,image/gif"
        @change="uploadImg(formId)"
      />
      <!--style="display: none"-->
    </form>
  </div>
</template>

<script>
import { quillEditor } from 'vue-quill-editor'
import Quill from 'quill'
import { ImageImport } from './imageImport'
import { ImageResize } from './imageResize'
import { shrinKImage, dataURLtoFile } from '@/utils/shrinkImage'
Quill.register('modules/imageImport', ImageImport)
Quill.register('modules/imageResize', ImageResize)

function handleCustomMatcher(node, Delta) {
  // 允许是http（s）开头的，赋默认值
  if (/http(s)?:\/\/\S|data:image\/png;base64\S/.test(node.src)) {
    Delta.ops = [{ insert: { image: node.src } }]
    return Delta
  }
}
//编译器配置
const editorOption = Object.freeze({
  theme: 'snow', // or 'bubble'
  placeholder: '输入点什么......',
  modules: {
    toolbar: {
      container: [
        ['bold', 'italic', 'underline', 'strike'],
        ['blockquote', 'code-block'],
        [{ header: 1 }, { header: 2 }],
        [{ list: 'ordered' }, { list: 'bullet' }],
        [{ script: 'sub' }, { script: 'super' }],
        [{ indent: '-1' }, { indent: '+1' }],
        [{ direction: 'rtl' }],
        [{ size: ['small', false, 'large', 'huge'] }],
        [{ header: [1, 2, 3, 4, 5, 6, false] }],
        [{ font: [] }],
        [{ color: [] }, { background: [] }],
        [{ align: [] }],
        ['clean'],
        ['link', 'image', 'video']
      ],
      handlers: {
        image: function(value) {
          // console.log'select value-->', value)
          if (value) {
            // 触发input框选择图片文件
            document.querySelector('.avatar-uploader input').click()
          } else {
            this.quill.format('image', false)
          }
        }
      }
    },
    imageImport: true,
    imageResize: {
      displaySize: true
    },
    clipboard: {
      // 粘贴版，处理粘贴时候带图片
      matchers: [['img', handleCustomMatcher]]
    }
  }
})
export default {
  name: 'vmqullEidtor',
  components: { quillEditor },
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    value: String,
    rest: Boolean,
    autoUpload: Boolean,
    needPreview: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      content: '',
      editorOption,

      editorContent: '',
      uniqueId: '',
      formId: '',
      imgPercent: 0,
      imageLoading: false,
      newOption: {
        placeholder: '请填写简介',
        history: {
          delay: 100,
          maxStack: 100,
          userOnly: false
        }
      },
      addImgRange: ''
    }
  },
  computed: {
    editor() {
      return this.$refs.myQuillEditor.quill
    }
  },
  methods: {
    onPreview() {
      const { content } = this
      this.$emit('preview', content)
    },
    //压缩图片
    async vmShrinkImage(
      { file, targetWidth = 500, targetHeight = 500, multiple = 0.8 },
      name = 'file.jpg'
    ) {
      try {
        const shrinkFile = await shrinKImage({
          file,
          width: targetWidth,
          height: targetHeight
        })
        const { url, blobFile, width, height } = shrinkFile
        //目标大小
        if (blobFile.size > 1024 * 1024) {
          await this.vmShrinkImage({
            file: blobFile,
            targetWidth: width * multiple,
            targetHeight: height * multiple,
            multiple
          })
        } else {
          return Promise.resolve(dataURLtoFile(url, name))
        }
      } catch (err) {
        // console.logerr)
        this.$message.error('文件压缩失败...')
        return Promise.reject('文件压缩失败...')
      }
    },
    async uploadImg(id) {
      try {
        const vm = this
        vm.imageLoading = true
        const formDom = document.getElementById(id)
        const file = formDom[0].files[0]
      //  const shrinkFile = await this.vmShrinkImage({ file })
        const shrinkFile = file
        const formData = new FormData()
        console.log(shrinkFile)
        formData.append('img ', shrinkFile)
        try {
          const url = await vm.uploadImgReq(shrinkFile) // 自定义的图片上传函数
          if (url != null && url.length > 0) {
            let value = url
            vm.addImgRange = vm.$refs.myQuillEditor.quill.getSelection()
            value = vm.$img(url)
            vm.$refs.myQuillEditor.quill.insertEmbed(
              vm.addImgRange != null ? vm.addImgRange.index : 0,
              'image',
              value,
              Quill.sources.USER
            )
          } else {
            vm.$message.warning('图片增加失败')
          }
          document.getElementById(vm.uniqueId).value = ''
        } catch ({ message: msg }) {
          document.getElementById(vm.uniqueId).value = ''
          vm.$message.warning(msg)
        }
        vm.imageLoading = false
      } catch (error) {
        console.log(error)
      }
    },
    async uploadImgReq(formdata) {
      try {
        let imgRes = await this.request({
            url: "/uploads/files",
            method: "post",
            dataType: "blob",
            loading:false,
            data: {
              img: formdata,
            },
          });
        return Promise.resolve(imgRes.content.img)
      } catch (error) {
        console.log(error)
        return Promise.reject(error)
      }
    }
  },
  created() {
    const vm = this
    vm.imgPercent = 0
    vm.editorContent = vm.text
    vm.uniqueId = vm.editorId ? vm.editorId : `inputImg_${Math.random() * 100}`
    vm.formId = `formId${Math.random() * 100}`
  },
  mounted() {
    const vm = this
    const imgHandler = async function(image) {
      vm.addImgRange = vm.$refs.myQuillEditor.quill.getSelection()
      if (image) {
        const fileInput = document.getElementById(vm.uniqueId) //隐藏的file文本ID
        fileInput.click() //加一个触发事件
      }
    }
    vm.$refs.myQuillEditor.quill
      .getModule('toolbar')
      .addHandler('image', imgHandler)
  },
  watch: {
    content(str) {
      this.$emit('change', str)
    },
    rest(state) {
      if (state) {
        this.content = ''
        this.$emit('onRest')
      }
    },
    value: {
      immediate: true,
      handler(v) {
        this.content = v
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.editor {
  line-height: initial;
}

/deep/.editor > .ql-container.ql-snow {
  border: 1px solid #cccccc;
}
.vm-eidtor-toolbar {
  border: 1px solid #ccc;
  border-bottom: none;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.toolbar-module {
  margin-left: auto;
  margin-right: 10px;
}
/deep/.ql-container > .ql-editor {
  min-height: 200px;
  max-height: 200px;
  overflow: auto;
}
/deep/ .ql-toolbar {
  border-top: none;
}
</style>
